package com.zhao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhao.bean.*;
import com.zhao.config.BaseContext;
import com.zhao.config.CustomException;
import com.zhao.dao.AddressBookDao;
import com.zhao.dao.OrderDetailDao;
import com.zhao.dao.OrdersDao;
import com.zhao.dao.ShoppingCartDao;
import com.zhao.dto.OrdersDto;
import com.zhao.service.AddressBookService;
import com.zhao.service.OrderDetailSrevice;
import com.zhao.service.OrdersService;
import com.zhao.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author HK
 */
@Service
@Slf4j
public abstract class OrderServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailSrevice orderDetailSrevice;

    //订单表
    @Autowired
    private OrdersDao ordersDao;

    //订单详细表
    @Autowired
    private OrderDetailDao orderDetailDao;

    //地址表
    @Autowired
    private AddressBookDao addressBookDao;

    //购物车表
    @Autowired
    private ShoppingCartDao shoppingCartDao;

    @Override
    @Transactional
    public void submit(Orders orders, User user) {

        Long userId = BaseContext.get();

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);

        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空，不能下单");
        }


        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookDao.selectById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("用户地址信息有误，不能下单");
        }

        long orderId = IdWorker.getId();

        AtomicInteger amount = new AtomicInteger(0);

        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        this.save(orders);

        orderDetailSrevice.saveBatch(orderDetails);

        shoppingCartService.remove(queryWrapper);

    }

    /**
     * 历史订单与
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public IPage<OrdersDto> selectpage(int page, int pageSize) {
        //创建条件对象
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        //设置查询条件
        lqw.eq(Orders::getUserId, BaseContext.get());//用户id
        lqw.orderByDesc(Orders::getCheckoutTime);    //根据时间排序
        //设置分页查询条件
        Page<Orders> ordersPage = new Page<Orders>(page, pageSize);
        //分页查询
        Page<Orders> ordersPage1 = ordersDao.selectPage(ordersPage, lqw);


        //自定义一个IPage<OrdersDto>用来保存total与getRecords
        IPage<OrdersDto> ordersDtoIPage = new Page<OrdersDto>();
        //保存total
        ordersDtoIPage.setTotal(ordersPage1.getTotal());
        //创建List集合用来存放每一条 OrdersDto数据（订单、订单详细）
        List<OrdersDto> orderDetailList = new ArrayList<>();

        //遍历ordersPage1中每一条订单数据，并获取每一条相关的DishDto数据（订单、订单详细）
        for (Orders record : ordersPage1.getRecords()) {
            //创建DishDto对象用来保存每一条信息（订单、订单详细）
            OrdersDto ordersDto = new OrdersDto();

            //1.封装订单数据
            BeanUtils.copyProperties(record, ordersDto);

            //2.封装订单详细数据
            //2.1获取订单id（也是订单详细表里面的getOrderId）
            Long id = record.getId();
            //2.2创建条件对象
            LambdaQueryWrapper<OrderDetail> lqwod = new LambdaQueryWrapper<>();
            //2.3设置查询条件
            lqwod.eq(OrderDetail::getOrderId, id);
            //2.4查询订单对应的订单详细
            List<OrderDetail> orderDetailList1 = orderDetailDao.selectList(lqwod);
            //2.5封装订单详细数据
            ordersDto.setOrderDetails(orderDetailList1);

            //2.6将每一个ordersDto封装到List<OrdersDto>中保存
            orderDetailList.add(ordersDto);
        }

        //将List<OrdersDto>集合封装到 IPage<OrdersDto>中Records中，并返回
        return ordersDtoIPage.setRecords(orderDetailList);

    }


    /**
     * 后台订单分页查询
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<Orders> findPage(PageParam pageParam) throws ParseException {
        // 转成date格式
       /*SimpleDateFormat format = new SimpleDateFormat("yyyy-DD-mm HH:mm:ss");
        Date beginTime = format.parse(pageParam.getBeginTime());
        Date endTime = format.parse(pageParam.getEndTime());*/

        // 设置模糊查询条件
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.like(pageParam.getNumber() != null, Orders::getNumber, pageParam.getNumber());
        qw.ge(pageParam.getBeginTime() != null, Orders::getOrderTime, pageParam.getBeginTime());
        qw.le(pageParam.getEndTime() != null, Orders::getOrderTime, pageParam.getEndTime());

        //分页查询
        Page<Orders> p = new Page<>(pageParam.getPage(), pageParam.getPageSize());
        return ordersDao.selectPage(p, qw);
    }


}
